//
//  ACDeviceInfoController.m
//  MonitoringSystem
//
//  Created by oilklenze on 16/6/21.
//  Copyright © 2016年 Interlube. All rights reserved.
//

#import "ACDeviceInfoController.h"
#import "MapGPSViewController.h"
#import "ACDeviceSettingController.h"
#import "KNCirclePercentView.h"
#import "ACInforCustomButtom.h"
#import "CustomProgress.h"
#import "NetRequestClass.h"
#import "UtilToolsClass.h"
#import "ACQRResultController.h"
#import "TYWaveProgressView.h"
#import "YLZHoledView.h"
#import "ACDeviceInfoModel.h"
#import "ACCustomAlertView.h"
#import "ACChangeAuthorController.h"

#import "ACWeakTimer.h"
@interface ACDeviceInfoController ()<YLZHoledViewDelegate>{
  
    NSTimer * timer;    // 定时器
    CGFloat leftPresent;  // 左边进度条的刻度
    CGFloat rightPresent;  // 右边进度条的刻度
    CGFloat deviceWorkTime;// 设备运行时间
    CGFloat deviceWaitTime;// 设备等待时间
    BOOL isNeedAnimation; // 是否需要动画加载
}
@property (nonatomic, weak) TYWaveProgressView *waveProgressView;

@property (weak, nonatomic) IBOutlet UILabel *lblDeviceName;// 设备名称
@property (weak, nonatomic) IBOutlet UILabel *lblDeviceImei; // 设备IMEI
@property(nonatomic,strong)  CustomProgress * cusLeftProgress; // 左边进度条
@property(nonatomic,strong)  CustomProgress * cusRightProgress; // 右边进度条
@property (weak, nonatomic) IBOutlet ACInforCustomButtom *proBtnSetting;
@property (weak, nonatomic) IBOutlet ACInforCustomButtom *proBtnGPS;
@property (weak, nonatomic) IBOutlet ACInforCustomButtom *proBtnFill;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *settingAndFillConstraint;
@property (weak, nonatomic) IBOutlet UIImageView *imgViewOilAnimation;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *fillAndGPSConstraint;
@property(nonatomic,strong) ACDeviceInfoModel * deviceInfoModel; // 数据结果
@property(nonatomic,weak) KNCirclePercentView * autoCalculateCircleView;// 旋转圆
@property (nonatomic, strong) YLZHoledView *holedView; //遮罩层
@property(nonatomic,weak) YLZHoledView  * ylzGuidView;// 引导视图
@property(nonatomic,weak) UIImageView * portDeviceLight; //设备背景图片
- (IBAction)btnFill:(id)sender;
- (IBAction)btnSetting:(id)sender;
- (IBAction)btnGPS:(id)sender;
@end

@implementation ACDeviceInfoController
/**
 *   从设备列表中进入设备详情，还是从泵芯配置小返回到设备详情，都是调用了请求数据的同一个接口。
 *   因为单独做数据UI更新过于麻烦，因此UI上，需要做懒加载处理，防止UI的重复addSubView.
 */
- (KNCirclePercentView *)autoCalculateCircleView{
    if (!_autoCalculateCircleView) {
        KNCirclePercentView *tAutoCalculateCircleView  = [[KNCirclePercentView alloc] init];
        [self.view addSubview:tAutoCalculateCircleView];
        _autoCalculateCircleView = tAutoCalculateCircleView;
    }
    return _autoCalculateCircleView;
}

- (CustomProgress *)cusLeftProgress{
    
    if (!_cusLeftProgress) {
        CustomProgress * tCusLeftProgress = [[CustomProgress alloc] init];
        [self.view addSubview:tCusLeftProgress];
        _cusLeftProgress = tCusLeftProgress;
    }
    return _cusLeftProgress;
    
}

-(CustomProgress *)cusRightProgress{
    if (!_cusRightProgress) {
        CustomProgress * tCusRightProgress = [[CustomProgress alloc] init];
        [self.view addSubview:tCusRightProgress];
        _cusRightProgress = tCusRightProgress;
    }
    return _cusRightProgress;
}


- (UIImageView *)portDeviceLight{
    if (!_portDeviceLight) {
        UIImageView * tPortDeviceLight = [[ UIImageView alloc] init];
        tPortDeviceLight.frame = CGRectMake(SCREEN_WIDTH * 0.5 - 125, SCREEN_HEIGHT * 0.5 - 200,250,250);
        [self.view addSubview:tPortDeviceLight];
        _portDeviceLight = tPortDeviceLight;
    }
    return _portDeviceLight;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    isNeedAnimation = false;
    self.title = NSLocalizedString(@"设备详情", nil);
    [self.proBtnGPS setTitle:NSLocalizedString(@"地图", nil) forState:UIControlStateNormal];
    [self.proBtnFill setTitle:NSLocalizedString(@"注油", nil) forState:UIControlStateNormal];
    [self.proBtnSetting setTitle:NSLocalizedString(@"设置", nil) forState:UIControlStateNormal];
    self.view.backgroundColor = ACCommentColor;

    // 设置返回按钮
    UIBarButtonItem* backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back@3x"] style:UIBarButtonItemStylePlain target:self action:@selector(backItemClick:)];
    backItem.tag = 0;
    self.navigationItem.leftBarButtonItem = backItem;
      self.navigationItem.hidesBackButton = YES;
    /*   添加约束   */
    [self initConstraint];

}

/**
 *  视图显示的时候，设定布局范围 ----- 因为设备信息界面，头部导航条的透明，影响了关联的界面
 *
 */
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsCompact];
    self.navigationController.navigationBar.translucent = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    /*   请求数据   */
    [self requestForData];
}


#pragma mark 视图就要显示完成时，开始判断是否需要加载引导图，是否要重置进度条
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    /*    判断是否需要添加引导图   默认值是false */
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSInteger isNeedMask = [[UD objectForKey:@"maskLayerGuid2"] intValue];
        if(isNeedMask){
            if (self.deviceInfoModel.isEmployer) { // 当前用户是管理者
                [self loadMaskView];
            }
        }
    });
    
    if ([[UD objectForKey:@"maskLayerGuid9"] intValue]) {
        // 引导9
        [self openFillMaskLayerForGuid9];
    }
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    // 移除界面设置为非编辑过状态
    [UD setObject:@(0) forKey:@"isEditDviceConfig"];
    isNeedAnimation = false;
    // 重置进度条
    [self recoverOil];
    // 释放定时器
    [self recoverTimer];

}

/**
 *  视图消失的时候，移除定时器
 *
 */
- (void)dealloc{
    NSLog(@"移除定时器  %s",__func__);
    [self recoverTimer];

}

- (void)backItemClick:(UIBarButtonItem *)sender{
    if (sender.tag) {
        // 权限
        ACChangeAuthorController * authorController = [[ACChangeAuthorController alloc] init];
        authorController.imei = self.i_imei;
        authorController.isDeviceInfoEnter = YES;
        [self.navigationController pushViewController:authorController animated:YES];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}


#pragma mark 添加遮罩指示 -----  引导进行泵芯配置
- (void) loadMaskView{
    YLZHoledView * tView = [[YLZHoledView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    tView.dimingColor = [UIColor clearColor];
    [[UIApplication sharedApplication].keyWindow addSubview:tView];
    self.ylzGuidView = tView;
    
    UIImageView * guidView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Guidxqsm"]];
    guidView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);

    [tView addSubview:guidView];
     // 我知道了
    UIButton * nextBtn = [[UIButton alloc] init];
    [nextBtn setImage:[UIImage imageNamed:@"Guiderwwozhidaole"] forState:UIControlStateNormal];
    [nextBtn sizeToFit];
    nextBtn.tag = 0;
    nextBtn.center = CGPointMake(SCREEN_WIDTH * 0.5, SCREEN_HEIGHT * 0.9);
    [tView addSubview:nextBtn];
    [nextBtn addTarget:self action:@selector(loadingDeviceGuid:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)loadingDeviceGuid:(UIButton *)sender{
  
    [self.ylzGuidView removeFromSuperview];
    
    self.holedView = [[YLZHoledView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    self.holedView.holeViewDelegate = self;
    // 圆形
    [self.holedView initWithMaskLayerWithObj:CGRectMake(SCREEN_WIDTH * 0.65,SCREEN_HEIGHT  * 0.8, 120, 120)
                                 layerRadius:80 fingerRect: CGPointMake(SCREEN_WIDTH * 0.8,SCREEN_HEIGHT * 0.95) holdViewTag:0];
    UIImageView * guidLableView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Guidshezhi"]];
    [guidLableView sizeToFit];
    guidLableView.layer.anchorPoint = CGPointMake(1, 1);
    guidLableView.center = CGPointMake(SCREEN_WIDTH * 0.8,SCREEN_HEIGHT  * 0.75);
    [self.holedView addSubview:guidLableView];
    [[UIApplication sharedApplication].keyWindow addSubview:self.holedView];
}

- (void)openFillMaskLayerForGuid9{
    self.holedView = [[YLZHoledView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    self.holedView.holeViewDelegate = self;
    UIImageView * guidLableView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Guiderwzhuyou"]];
    [guidLableView sizeToFit];
    guidLableView.center = CGPointMake(SCREEN_WIDTH * 0.5,SCREEN_HEIGHT - 160);
    [self.holedView addSubview:guidLableView];
    [self.holedView initWithMaskLayerWithObj:CGRectMake(SCREEN_WIDTH * 0.4 - 20,SCREEN_HEIGHT - 120,100,100)
                                 layerRadius:50 fingerRect: CGPointMake(SCREEN_WIDTH * 0.5 ,SCREEN_HEIGHT - 30) holdViewTag:1];
    [[UIApplication sharedApplication].keyWindow addSubview:self.holedView];
}


- (void)holedView:(YLZHoledView *)holedView didSelectHoleAtIndex:(NSUInteger)index{
    if (holedView.tag == 0) {
        if(index == 0){ // 点中指定区域，进行配置引导
            [self.holedView removeFromSuperview];
            [UD setObject:@(0) forKey:@"maskLayerGuid2"];
            [UD setObject:@(1) forKey:@"maskLayerGuid3"];
            ACDeviceSettingController * settingController = [[ACDeviceSettingController alloc] init];
            settingController.imei = self.i_imei;
            settingController.deviceNumber = self.deviceInfoModel.number;
            settingController.zone = self.deviceInfoModel.zone;
            settingController.isEmployer = self.deviceInfoModel.isEmployer;
            settingController.employer = self.deviceInfoModel.employer;
            [self.navigationController pushViewController:settingController animated:YES];
        }
    }
    if (holedView.tag == 1) {
        if(index == 0){ // 点中指定区域，进行配置引导
            [UD setObject:@(0) forKey:@"maskLayerGuid9"];
            [UD setObject:@(1) forKey:@"maskLayerGuid1"];
            [self.holedView removeFromSuperview];
            [self btnFill:nil];
        }
    }
}



- (void) initConstraint{
    if (SCREEN_HEIGHT == 568) {}
    else if (SCREEN_HEIGHT == 667) {
        // 4.7
        self.settingAndFillConstraint.constant  = self.settingAndFillConstraint.constant + 10;
        self.fillAndGPSConstraint.constant  = self.fillAndGPSConstraint.constant + 10;
    }
    else if (SCREEN_HEIGHT == 736) {
        //5.5
        self.settingAndFillConstraint.constant  = self.settingAndFillConstraint.constant + 20;
        self.fillAndGPSConstraint.constant  = self.fillAndGPSConstraint.constant + 20;
    }
    self.proBtnSetting.titleEdgeInsets = UIEdgeInsetsMake(20, 0, 0, 0);
    self.proBtnFill.titleEdgeInsets = UIEdgeInsetsMake(20, 0, 0, 0);
    self.proBtnGPS.titleEdgeInsets = UIEdgeInsetsMake(20, 0, 0, 0);
}

#pragma mark 请求数据
- (void) requestForData{
    [[UtilToolsClass getUtilTools] addDoLoading];
    NSDictionary * param = @{@"i_imei":self.i_imei}; 
    __weak typeof(self)weakSelf = self;
    [NetRequestClass requestWithUrlForGetDeviceInfo:self andUrl:[REQUESTHEADER stringByAppendingString:@"deviceList/queryDevice.asp"] andParam:param success:^(ACDeviceInfoModel *result) {
        [[UtilToolsClass getUtilTools] removeDoLoading];
        [weakSelf updateUI:result];
    } failure:^(NSString *failure) {
        [[UtilToolsClass getUtilTools] removeDoLoading];
    }];
}


#pragma mark 加载UI ------------- 无动画效果的 ----------------
- (void)updateUI:(ACDeviceInfoModel *) result{
    self.deviceInfoModel = result;
    NSString * nickName = @"";
    if (![result.nickname isEqualToString:@""]) {
        nickName = result.nickname;
    }else{
        nickName = @"---";
    }
    self.lblDeviceName.text = nickName;
    self.lblDeviceImei.text = self.i_imei;

    if(self.deviceInfoModel.isEmployer){// 如果用户是该台设备的管理者，那么就有进入下一集界面的入口
        UIBarButtonItem* changeDeviceAuthorItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon-guanlizhuangyi"] style:UIBarButtonItemStylePlain target:self action:@selector(backItemClick:)];
        changeDeviceAuthorItem.tag = 1;
        self.navigationItem.rightBarButtonItem = changeDeviceAuthorItem;
        self.navigationItem.hidesBackButton = YES;
    }
    // 加载UI
    [self initUI];
}

#pragma mark 加载UI ------------- 有动画效果的 ----------------
- (void) initUI{

    // 横行进度条
    [self loadingCustomProgress];
    // 油桶动画
    [self loadingWaveProgressView];
}


#pragma mark 加载进度条
- (void) loadingCustomProgress{
    
    //设置     进度条
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"DeviceShift" ofType:@"plist"];
    NSDictionary *usersDic = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
    CGFloat currentDeviceWorkTime =  [usersDic[@"-1档位"] floatValue];
    CGFloat deviceAllWorkTime =  [usersDic[[NSString stringWithFormat:@"%@档位",@(self.deviceInfoModel.shift)]] floatValue] ;
    // 档位的一个周期的时间
    CGFloat deviceCurrentWaitTime = deviceAllWorkTime - currentDeviceWorkTime;// 等待的时间
    deviceWorkTime = currentDeviceWorkTime;
    deviceWaitTime = deviceCurrentWaitTime;
    
    leftPresent = 0;
    rightPresent = 0;
    CGSize screenSize =  [UIScreen mainScreen].bounds.size;
    CGFloat cusProgressX = 20;
    CGFloat cusProgressY = screenSize.height * 0.5 + 20;
    CGFloat  cusProgressW = screenSize.width - cusProgressX * 2;
    CGFloat spaceW = cusProgressW / 4.0;
    
    // 背景
    UIImageView * BGView = [[UIImageView alloc] initWithFrame:CGRectMake(cusProgressX,cusProgressY , cusProgressW, 22)];
    BGView.image = [UIImage imageNamed:@"bar-yunxing-bg_2"];
    [self.view addSubview:BGView];
    CGFloat cusLeftProgressW = 0;
    UIImage * tempCusProgressView;
    if (self.deviceInfoModel.shift == 1) {// 如果是一档的话，非持续运行，那么其宽度就不一样
        cusLeftProgressW =  cusProgressW;
        tempCusProgressView = [UIImage imageNamed:@"cusProgress_lv"];
    }else{
        cusLeftProgressW = spaceW * 3;
        tempCusProgressView = [UIImage imageNamed:@"bar-tingzhi"];
    }
    [self.cusLeftProgress initProgressWithFrame: CGRectMake(cusProgressX,cusProgressY , cusLeftProgressW, 22) BGImage:[UIImage imageNamed:@"bar-yunxing-bg_2"] leftImage:tempCusProgressView guidImage:[UIImage imageNamed:@"light"] maxFloat:100];
    
    [self.cusRightProgress initProgressWithFrame:CGRectMake(CGRectGetMaxX(self.cusLeftProgress.frame), cusProgressY, spaceW , 22) BGImage:nil leftImage:[UIImage imageNamed:@"bar-yunxing"] guidImage:[UIImage imageNamed:@"light"] maxFloat:100];
    [self.view bringSubviewToFront:self.cusRightProgress];
    [self.view bringSubviewToFront:self.cusLeftProgress];
    
    // 总时间
    CGFloat lblAllWorkTimeY = CGRectGetMaxY(self.cusLeftProgress.frame) + 10;
    CGFloat lblAllWorkTimeX = SCREEN_WIDTH * 0.5 - 50;
    UILabel * lblAllWorkTime = [[UILabel alloc] initWithFrame:CGRectMake(lblAllWorkTimeX , lblAllWorkTimeY , 100, 30)];
    lblAllWorkTime.text = [NSString stringWithFormat:@"%.1fMIN",deviceAllWorkTime];
    lblAllWorkTime.textColor = [UIColor whiteColor];
    lblAllWorkTime.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:lblAllWorkTime];
    
    //运行时间
    CGFloat lblWorkTimeY = CGRectGetMinY(self.cusRightProgress.frame) - 5;
    CGFloat lblWorkTimeX = CGRectGetMidX(self.cusRightProgress.frame) - 50;
    UILabel * lblWorkTime = [[UILabel alloc] initWithFrame:CGRectMake(lblWorkTimeX , lblWorkTimeY, 100, 30)];
    lblWorkTime.text = [NSString stringWithFormat:@"%.1fMIN",deviceWorkTime];
    lblWorkTime.textColor = [UIColor whiteColor];
    lblWorkTime.textAlignment = NSTextAlignmentCenter;
    lblWorkTime.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:lblWorkTime];
    
    if (self.deviceInfoModel.shift != 1) {
        // 间隔线
        UIImageView * BGRightView = [[UIImageView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.cusLeftProgress.frame) - 1,cusProgressY,1, 22)];
        BGRightView.image = [UIImage imageNamed:@"RGB132-255-0"];
        [self.view addSubview:BGRightView];
        //停顿时间
        CGFloat lblWaitTimeY = CGRectGetMinY(self.cusLeftProgress.frame) - 5;
        CGFloat lblWaitTimeX = CGRectGetMidX(self.cusLeftProgress.frame) ;
        UILabel * lblWaitTime = [[UILabel alloc] initWithFrame:CGRectMake(lblWaitTimeX - 15, lblWaitTimeY, 100, 30)];
        lblWaitTime.text = [NSString stringWithFormat:@"%.1fMIN",deviceWaitTime];
        lblWaitTime.textColor = [UIColor whiteColor];
        lblWaitTime.font = [UIFont systemFontOfSize:14];
        [self.view addSubview:lblWaitTime];
    }else{
        // 如果是0档，进度条的长度为2.5分钟
        deviceWaitTime = 2.5 ;
        lblWorkTime.frame = CGRectMake(SCREEN_WIDTH * 0.5 - 50 , lblWorkTimeY, 100, 30);
    }
}

/**
 *  进行加油操作。会获取到当前设备的状态、运行时间。如果是状态3，4，非作业跟马达报警状态的话，就不产生进度条
 *
 */
- (void)adjustProgressView:(int)i_state runTime:(int)runTime{

    // 进度条时间的修正
     [self recoverOil];
     [self recoverTimer];
    // 根据设备状态，获取到此刻它进行的时间
    

        if (self.deviceInfoModel.i_state == 1) {
            leftPresent = 100;
            CGFloat runTimeX = (runTime *100.0 / (2.5 * 60));
            if (runTimeX > 2.5 * 60) {
                runTimeX = 0;
            }
             isNeedAnimation = true;
            rightPresent = runTimeX;
            if (self.deviceInfoModel.shift == 1) {// 如果是1档的话，只有一条进度条，那么就上述的rightPresent值给过leftPresent即可。
                leftPresent = rightPresent;
            }
        }else if (self.deviceInfoModel.i_state == 2){
            // 停止
            CGFloat stopTimeX = (runTime *100.0 / (deviceWaitTime * 60));
            if (stopTimeX > deviceWaitTime * 60) {
                stopTimeX = 0;
            }
            isNeedAnimation = true;
            leftPresent = stopTimeX;
            rightPresent = 0;
            
        }else if (self.deviceInfoModel.i_state == 3 || self.deviceInfoModel.i_state == 4){
            return;
        }
        timer = [HWWeakTimer scheduledTimerWithTimeInterval:1 block:^(id userInfo) {
            [self timerCallBack];
        } userInfo:nil repeats:YES];
        [timer fire];
}

- (void)timerCallBack{
    // 如果是一档的话，持续运行，走左边的进度条，如果是其他档位，有分运行状态跟停止状态
    if (self.deviceInfoModel.shift == 1) {
        [self leftTimerCallBack];
    }else{
        if (self.deviceInfoModel.i_state == 1) {
            // 运行状态
            [self rightTimerCallBack];
        }else if (self.deviceInfoModel.i_state == 2){
            // 停止状态
            [self leftTimerCallBack];
        }

    }
 }

-(void)leftTimerCallBack{
//    NSLog(@"leftTimerCallBack %p",&timer);
    if (leftPresent < 100) {
        if (isNeedAnimation) {
            [UIView animateWithDuration:0.8 animations:^{
                [ self.cusLeftProgress setPresent:leftPresent];
            } completion:^(BOOL finished) {
                if (finished) {
                    [self.cusLeftProgress showGuidImageViewAnimation];
                    [self.cusLeftProgress moveGuidViewX:self.cusLeftProgress.frame.size.width/self.cusLeftProgress.maxValue * leftPresent - 2 y:5];
                }
            }];
            isNeedAnimation = false;
        }else{
            [ self.cusLeftProgress setPresent:leftPresent];
            [self.cusLeftProgress moveGuidViewX:self.cusLeftProgress.frame.size.width/self.cusLeftProgress.maxValue * leftPresent - 2 y:5];
        }
       leftPresent +=  (100.0 / (deviceWaitTime * 60));
    }else{
        if (self.deviceInfoModel.shift != 1) {
            [self.cusLeftProgress stopGuidImageViewAnimtion];
            isNeedAnimation = true;
            rightPresent = 0;
            self.deviceInfoModel.i_state = 1;
        }else{
            leftPresent = 0.0;// 如果是0档，设备一直运行
        }
    }
}


-(void)rightTimerCallBack{
   NSLog(@"rightTimerCallBack %p",&timer);
    if (rightPresent < 100) {
        if (isNeedAnimation) {
            [UIView animateWithDuration:0.8 animations:^{
                [self.cusLeftProgress setPresent:leftPresent];
                
            } completion:^(BOOL finished) {
                if (finished) {
                    [UIView animateWithDuration:0.8 animations:^{
                          [self.cusRightProgress setPresent:rightPresent];
                    } completion:^(BOOL finished) {
                        if (finished) {
                            [self.cusRightProgress showGuidImageViewAnimation];
                            [self.cusRightProgress moveGuidViewX:CGRectGetMaxX(self.cusRightProgress.leftimgView.frame) y:5];//
                        }
                    }];
                }
            }];
            isNeedAnimation = false;
        }else{
            [self.cusRightProgress setPresent:rightPresent];
            [self.cusRightProgress moveGuidViewX:CGRectGetMaxX(self.cusRightProgress.leftimgView.frame) y:5];
        }
        rightPresent += (100.0 / (2.5 * 60));
    }else{
        /**
         *  定时器暂停，处理右边运行时的逻辑代码stopGuidImageViewAnimtion。如果不暂时，会偶现stopGuidImageViewAnimtion执行速度居然没有
            定时器的快问题，造成cusRightProgress不移除。暂停，然后在开启定时器即可。
         */
        [timer setFireDate:[NSDate distantFuture]];
        leftPresent = 0;
        isNeedAnimation = true;
        rightPresent = 0;
        [self.cusRightProgress setPresent:rightPresent];
        [self.cusRightProgress stopGuidImageViewAnimtion];
        self.deviceInfoModel.i_state = 2;
        // 开启定时器
        [timer setFireDate:[NSDate date]];
    }
}

#pragma mark 加载油桶动画
- (void)loadingWaveProgressView{
    CGFloat waveProgressViewW = 160;
    CGFloat waveProgressViewH = 160;
    
    // 亮光
    if (self.portDeviceLight.isAnimating) {
        [self.portDeviceLight stopAnimating];
    }
    if (self.deviceInfoModel.i_state == 1 || self.deviceInfoModel.i_state == 2) {
        self.portDeviceLight.image = [UIImage imageNamed:@"lightBlue"];
       
    }else{
        self.portDeviceLight.image = [UIImage imageNamed:@"lightRed"];
        [UIView animateWithDuration:0.5 delay:0.0 options:UIViewAnimationOptionRepeat animations:^{
            self.portDeviceLight.alpha = 0.7;
            self.portDeviceLight.transform = CGAffineTransformMakeScale(0.9, 0.9);
        } completion:^(BOOL finished) {
            self.portDeviceLight.alpha = 1;
            self.portDeviceLight.transform = CGAffineTransformMakeScale(1.1, 1.1);
        }];
    }
    [self.view addSubview:self.portDeviceLight];
    
    // 背景
    UIImageView * portDeviceBG = [[ UIImageView alloc] init];
    if ([self.deviceInfoModel.type isEqualToString:@"AC2"]) {
        portDeviceBG.image = [UIImage imageNamed:@"AC2beng-buluok"];
    }else{
        portDeviceBG.image = [UIImage imageNamed:@"AC3beng-buluok"];
    }
    portDeviceBG.frame = CGRectMake(SCREEN_WIDTH * 0.5 - waveProgressViewW * 0.5, SCREEN_HEIGHT * 0.4 - waveProgressViewH + 20, waveProgressViewW, waveProgressViewH );
    [self.view addSubview:portDeviceBG];
   
    // 油桶动画
    TYWaveProgressView *waveProgressView = [[TYWaveProgressView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH * 0.5 - waveProgressViewW * 0.5, SCREEN_HEIGHT * 0.4 - waveProgressViewH + 20, waveProgressViewW, waveProgressViewH)];
    waveProgressView.waveViewMargin = UIEdgeInsetsMake(0, 12, 12, 12);
    if ([self.deviceInfoModel.type isEqualToString:@"AC2"]) {
         waveProgressView.backgroundImageView.image = [UIImage imageNamed:@"AC2beng"];
    }else{
         waveProgressView.backgroundImageView.image = [UIImage imageNamed:@"AC23beng"];
    }
    waveProgressView.numberLabel.text = [NSString stringWithFormat:@"%.f",self.deviceInfoModel.end_oil];
    waveProgressView.numberLabel.font = [UIFont boldSystemFontOfSize:36];
    waveProgressView.numberLabel.textColor = [UIColor whiteColor];
    waveProgressView.unitLabel.text = @"%";
    waveProgressView.unitLabel.font = [UIFont boldSystemFontOfSize:20];
    waveProgressView.unitLabel.textColor = [UIColor whiteColor];
    waveProgressView.percent =  self.deviceInfoModel.end_oil * 0.72 / 100.0;
    NSLog(@"waveProgressView.percent :%f",waveProgressView.percent);
     [waveProgressView startWave];
    [self.view addSubview:waveProgressView];
   
    _waveProgressView = waveProgressView;
    __weak typeof(self)weakSelf = self;
    [waveProgressView returnCallBack:^{
       // 运行进度条   根据设备状态，获取到此刻它进行的时间
        [weakSelf adjustProgressView:weakSelf.deviceInfoModel.i_state runTime:weakSelf.deviceInfoModel.runTime];
    }];
    
    [self.view bringSubviewToFront:waveProgressView];
    
    // 端口数 --------- AC2 -------- AC3
    UIImageView * portDeviceCount = [[ UIImageView alloc] init];
    if ([self.deviceInfoModel.type isEqualToString:@"AC2"]) {
        portDeviceCount.image = [UIImage imageNamed:@"AC2bengxin"];
    }else{
        portDeviceCount.image = [UIImage imageNamed:@"AC3bengxin"];
    }
    [portDeviceCount sizeToFit];
    portDeviceCount.center = CGPointMake(SCREEN_WIDTH * 0.5,CGRectGetMaxY(waveProgressView.frame) + 20 );
    [self.view addSubview:portDeviceCount];
    
    
    if (self.deviceInfoModel.i_state != 5) {
        // 档位 背景
        UIImageView * shiftView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"dangwei"]];
        [shiftView sizeToFit];
        shiftView.center = CGPointMake(CGRectGetMidX(waveProgressView.frame), CGRectGetMaxY(portDeviceCount.frame) - 22);
            [self.view addSubview:shiftView];
        
        // 档位数
        UILabel * shiftLable = [[UILabel alloc] initWithFrame:shiftView.frame];
        shiftLable.text = [NSString stringWithFormat:@"%d %@",(int)self.deviceInfoModel.shift - 1,NSLocalizedString(@"档", nil)];//
        shiftLable.textColor = [UIColor whiteColor];
        shiftLable.font = [UIFont systemFontOfSize:16];
        shiftLable.textAlignment = NSTextAlignmentCenter;
            [self.view addSubview:shiftLable];
        
    }
    
 


}

#pragma mark 加油动画
- (IBAction)btnFill:(id)sender {
    if(self.deviceInfoModel.isEmployer){
         [self addOilSuccessCallBack:nil];
        // 发送数据给后台
        [[UtilToolsClass getUtilTools] addDoLoading];
        __weak typeof(self)weakSelf = self;
        [NetRequestClass requestWithUrlForAddOil:self andUrl:[REQUESTHEADER stringByAppendingString:@"deviceList/addOil.asp"] andParam:@{@"i_imei":self.i_imei} success:^(NSDictionary* result) {
            [[UtilToolsClass getUtilTools] removeDoLoading];
            
            if(![result[@"result"] intValue]){
                [weakSelf addOilSuccessCallBack:result];
            }
        } failure:^(NSString *failure) {
            [[UtilToolsClass getUtilTools] removeDoLoading];
        }];
    }else{
        //存在管理者 UIAlertView
        ACCustomAlertView * alertView = [[ACCustomAlertView alloc] initAlertViewWithFrame:CGRectMake(SCREEN_WIDTH * 0.1, SCREEN_HEIGHT * 0.5 - 80, SCREEN_WIDTH * 0.8, 160) andSuperView:self.view];
        [alertView createTitle:NSLocalizedString(@"提示", nil) message:[NSString stringWithFormat:@"%@:+%@ %@%@",NSLocalizedString(@"该设备已被",nil),self.deviceInfoModel.zone,self.deviceInfoModel.employer,NSLocalizedString(@"用户绑定",nil)] calcelButton:@"" okButton:NSLocalizedString(@"确定",nil)];
        [[UIApplication sharedApplication].keyWindow addSubview:alertView];
    }
}


- (void) addOilSuccessCallBack:(NSDictionary *)dic{

    [self recoverTimer];
    [self recoverOil];
    isNeedAnimation = YES;
    _waveProgressView.numberLabel.text = @"100";
    _waveProgressView.percent = self.deviceInfoModel.end_oil * 0.72 / 100.0; // 0.7就是可以加满了。
    [_waveProgressView startWave];
    self.deviceInfoModel.end_oil = [dic[@"end_oil"] intValue];
    self.deviceInfoModel.i_state = [dic[@"i_state"] intValue];
    self.deviceInfoModel.runTime = [dic[@"runTime"] intValue];
    self.deviceInfoModel.setTime = [dic[@"setTime"] intValue];
    self.deviceInfoModel.end_day = [dic[@"end_day"] floatValue];
    self.deviceInfoModel.averageOil = [dic[@"averageOil"] floatValue];
 
    __weak typeof(self)weakSelf = self;
    [_waveProgressView returnCallBack:^{
        // 运行进度条   根据设备状态，获取到此刻它进行的时间
        [weakSelf adjustProgressView: self.deviceInfoModel.i_state runTime:self.deviceInfoModel.runTime];
    }];
}




#pragma mark 泵芯配置
- (IBAction)btnSetting:(id)sender {
    ACDeviceSettingController * settingController = [[ACDeviceSettingController alloc] init];
    settingController.imei = self.i_imei;
    settingController.deviceNumber = self.deviceInfoModel.number;
    settingController.zone = self.deviceInfoModel.zone;
    settingController.isEmployer = self.deviceInfoModel.isEmployer;
    settingController.employer = self.deviceInfoModel.employer;
    [self.navigationController pushViewController:settingController animated:YES];
}

#pragma mark GPS定位
- (IBAction)btnGPS:(id)sender {
    MapGPSViewController * mapViewController = [[MapGPSViewController alloc] init];
    mapViewController.device_IMEI = self.i_imei;
    mapViewController.isEnterSetting = false;
    [self.navigationController pushViewController:mapViewController animated:YES];
}




#pragma mark 复原定时器
- (void)recoverTimer{
    if (timer) {
        //停止定时器
        timer.fireDate = [NSDate distantFuture];
        [timer invalidate];
    }
    timer = nil;
}


#pragma mark 复原进度条
- (void)recoverOil{
    leftPresent = 0;
    rightPresent = 0;
    if (self.cusLeftProgress) {
        [self.cusLeftProgress setPresent:leftPresent];
        [self.cusLeftProgress stopGuidImageViewAnimtion];
    }
    if (self.cusRightProgress) {
        [self.cusRightProgress setPresent:rightPresent];
        [self.cusRightProgress stopGuidImageViewAnimtion];
    }
}

@end
